<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">捐赠记录管理</span>
          <div class="right">
            <el-button type="primary" @click="handleAdd">新增捐赠记录</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="捐赠人" prop="donorName">
          <el-input
            v-model="queryParams.donorName"
            placeholder="请输入捐赠人姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="queryParams.projectId" placeholder="请选择捐赠项目" clearable style="width: 200px">
            <el-option
              v-for="item in projectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="捐赠时间" prop="donationTime">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="donationList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column prop="projectId" label="捐赠项目" min-width="120">
          <template #default="{ row }">
            {{ getProjectName(row.projectId) }}
          </template>
        </el-table-column>
        <el-table-column prop="donorName" label="捐赠人" min-width="120" />
        <el-table-column prop="donationAmount" label="捐赠金额" min-width="120">
          <template #default="{ row }">
            ¥ {{ row.donationAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="donationMessage" label="捐赠留言" min-width="180" show-overflow-tooltip />
        <el-table-column prop="donationTime" label="捐赠时间" min-width="160" sortable>
          <template #default="{ row }">
            {{ row.donationTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加/编辑对话框 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        append-to-body
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="donation-form"
        >
          <el-form-item label="捐赠项目" prop="projectId">
            <el-select v-model="form.projectId" placeholder="请选择捐赠项目" style="width: 100%">
              <el-option
                v-for="item in projectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="捐赠人" prop="donorName">
            <el-input v-model="form.donorName" placeholder="请输入捐赠人姓名" />
          </el-form-item>
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="form.userId" placeholder="请输入用户ID（可选）" />
          </el-form-item>
          <el-form-item label="捐赠金额" prop="donationAmount">
            <el-input-number
              v-model="form.donationAmount"
              :precision="2"
              :step="100"
              :min="0"
              style="width: 100%"
              placeholder="请输入捐赠金额"
            />
          </el-form-item>
          <el-form-item label="捐赠留言" prop="donationMessage">
            <el-input
              v-model="form.donationMessage"
              type="textarea"
              :rows="3"
              placeholder="请输入捐赠留言"
            />
          </el-form-item>
          <el-form-item label="捐赠时间" prop="donationTime">
            <el-date-picker
              v-model="form.donationTime"
              type="datetime"
              placeholder="请选择捐赠时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 详情对话框 -->
      <el-dialog
        title="捐赠详情"
        v-model="detailDialogVisible"
        width="500px"
        append-to-body
        destroy-on-close
      >
        <div v-if="detailForm" class="donation-detail">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="捐赠项目">{{ getProjectName(detailForm.projectId) }}</el-descriptions-item>
            <el-descriptions-item label="捐赠人">{{ detailForm.donorName }}</el-descriptions-item>
            <el-descriptions-item label="用户ID">{{ detailForm.userId || '无' }}</el-descriptions-item>
            <el-descriptions-item label="捐赠金额">¥ {{ detailForm.donationAmount }}</el-descriptions-item>
            <el-descriptions-item label="捐赠留言">{{ detailForm.donationMessage || '无' }}</el-descriptions-item>
            <el-descriptions-item label="捐赠时间">{{ detailForm.donationTime }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DonationRecordAPI from '@/api/genealogy/donation.api'
import FundProjectAPI from '@/api/genealogy/fund-project.api'
import Pagination from '@/components/Pagination'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  donorName: '',
  projectId: undefined,
  beginTime: undefined,
  endTime: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  projectId: undefined,
  donorName: '',
  userId: undefined,
  donationAmount: 0,
  donationMessage: '',
  donationTime: undefined
})

// 表单校验规则
const rules = {
  projectId: [{ required: true, message: '请选择捐赠项目', trigger: 'change' }],
  donorName: [{ required: true, message: '请输入捐赠人姓名', trigger: 'blur' }],
  donationAmount: [{ required: true, message: '请输入捐赠金额', trigger: 'blur' }],
  donationTime: [{ required: true, message: '请选择捐赠时间', trigger: 'change' }]
}

// 项目选项
const projectOptions = ref([])

// 页面数据
const loading = ref(false)
const donationList = ref([])
const total = ref(0)
const dateRange = ref([])
const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const detailDialogVisible = ref(false)
const detailForm = ref(null)
const formRef = ref(null)
const queryForm = ref(null)

// 获取项目选项
const getProjectOptions = async () => {
  try {
    const res = await FundProjectAPI.getPage({ pageSize: 100 })
    projectOptions.value = (res.list || []).map(item => ({
      value: item.id,
      label: item.projectName
    }))
  } catch (error) {
    console.error('获取项目列表失败', error)
  }
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await DonationRecordAPI.getPage(queryParams)
    donationList.value = res.list || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取捐赠记录列表失败', error)
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryForm.value?.resetFields()
  dateRange.value = []
  queryParams.beginTime = undefined
  queryParams.endTime = undefined
  handleQuery()
}

// 日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    queryParams.beginTime = val[0]
    queryParams.endTime = val[1]
  } else {
    queryParams.beginTime = undefined
    queryParams.endTime = undefined
  }
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新增捐赠记录'
  // 使用格式化后的当前时间
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  form.donationTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  dialogVisible.value = true
}

// 编辑按钮操作
const handleEdit = async (row) => {
  resetForm()
  dialogTitle.value = '编辑捐赠记录'
  const id = row.id || row
  try {
    loading.value = true
    const res = await DonationRecordAPI.getFormData(id)
    Object.assign(form, res)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取捐赠记录详情失败', error)
  } finally {
    loading.value = false
  }
}

// 详情按钮操作
const handleDetail = async (row) => {
  const id = row.id || row
  try {
    loading.value = true
    const res = await DonationRecordAPI.getFormData(id)
    detailForm.value = res
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取捐赠记录详情失败', error)
  } finally {
    loading.value = false
  }
}

// 删除按钮操作
const handleDelete = (row) => {
  const ids = row.id || selectedRows.value.map(item => item.id).join(',')
  if (!ids) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm('确认删除所选捐赠记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await DonationRecordAPI.deleteByIds(ids)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除捐赠记录失败', error)
    }
  }).catch(() => {})
}

// 表单提交
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    
    try {
      loading.value = true
      if (form.id) {
        // 编辑
        await DonationRecordAPI.update(form.id, form)
        ElMessage.success('修改成功')
      } else {
        // 新增
        await DonationRecordAPI.create(form)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('保存捐赠记录失败', error)
    } finally {
      loading.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  form.id = undefined
  form.projectId = undefined
  form.donorName = ''
  form.userId = undefined
  form.donationAmount = 0
  form.donationMessage = ''
  form.donationTime = undefined
}

// 获取项目名称
const getProjectName = (projectId) => {
  const project = projectOptions.value.find(item => item.value === projectId)
  return project ? project.label : '未知项目'
}

// 页面加载时获取数据
onMounted(() => {
  getProjectOptions()
  getList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .title {
    font-size: 18px;
    font-weight: bold;
  }
}

.search-form {
  margin-bottom: 20px;
}

.donation-form {
  padding: 20px 0;
}

.donation-detail {
  padding: 10px;
}
</style>
